import aiomysql
import asyncio_redis
import tornado.web
import tornado.ioloop
import tornado.locks
import tornado.gen
import config
from urls import urlsList
from logging.config import dictConfig


async def __redis_init():
    return await asyncio_redis.Pool.create(
        host=config.REDIS_CONFIG["host"],
        port=config.REDIS_CONFIG["port"],
        db=config.REDIS_CONFIG["db"],
        password=config.REDIS_CONFIG["password"],
        poolsize=config.REDIS_CONFIG["poolsize"]
    )


async def __mysql_init():
    return await aiomysql.create_pool(
        host=config.MYSQL_CONFIG["host"],
        port=config.MYSQL_CONFIG["port"],
        minsize=config.MYSQL_CONFIG["minsize"],
        maxsize=config.MYSQL_CONFIG["maxsize"],
        user=config.MYSQL_CONFIG["user"],
        password=config.MYSQL_CONFIG["password"],
        db=config.MYSQL_CONFIG["db"],
        cursorclass=aiomysql.cursors.DictCursor
    )


class Application(tornado.web.Application):

    def __init__(self, mysql_db, redis_db):
        # 配置日志
        dictConfig(config.LOG_CONFIG)

        # 数据库初始化配置
        self.mysql_db = mysql_db
        self.redis_db = redis_db

        # url配置
        handlers = urlsList

        # 继承父类
        super(Application, self).__init__(handlers, **config.SETTING)


async def make_app():
    redis_db = await __redis_init()
    mysql_db = await __mysql_init()
    app = Application(mysql_db, redis_db)
    # 单进程模式
    # app.listen(config.PORT) 
    # 多进程模式
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(config.PORT)
    http_server.start(0)  
    shutdown_event = tornado.locks.Event()
    await shutdown_event.wait()


if __name__ == '__main__':
    tornado.ioloop.IOLoop.current().run_sync(make_app)

